// pages/car/index/index.js
const app = getApp()
var tab = require('../../../components/tab/tab.js');
// var cityData = require('../../../utils/citydatas.js');
Page({
    data: {
        showLoad: false, // 装货地弹出层
        type: '',// 判断点击哪个省市区
        province_zid: '', // 装货省
        city_zid: '', // 装货市
        area_zid: '', // 装货区
        province_zidz: '', // 装货省(调接口传值)
        city_zidz: '', // 装货市(调接口传值)
        area_zidz: '', // 装货区(调接口传值)
        type_zid:'', // 判断装货地是否滑动
        region: '请选择装货地',
        installColor: '#999', // 装货地颜色
        installBold: '400', // 装货地字体加粗
        showLoads: false, // 卸货地弹出层
        province_xid: '', // 卸货省
        city_xid: '', // 卸货市
        area_xid: '', // 卸货区
        province_xidx: '', // 卸货省(调接口传值)
        city_xidx: '', // 卸货市(调接口传值)
        area_xidx: '', // 卸货区(调接口传值)
        type_xid:'', // 判断卸货地是否滑动
        regionTwo: "请选择卸货地",
        removeColor: '#999', //卸货地颜色
        removeBold: '400', // 卸货地字体加粗
        addressKeyList:[0,0,0], // 获取当前选择索引
        citysData: [],
        provinces_z: [],
        citys_z: [],
        areas_z: [],
        value_z: [0,0,0],
        provinces_x: [],
        citys_x: [],
        areas_x: [],
        value_x: [0,0,0],
        showThree: false,// 货物分类弹出层
        columns: [], // 显示数组
        regionThree: ['必填，请输入货物分类'],
        mustColor: '#999', // 货物分类颜色
        showFour: false, // 时间筛选弹出层
        regionFour: ['必填，请输入送货时间'],
        regionFours:"", // 显示
        timeColor: '#999', // 时间颜色
        currentDate: new Date().getTime(),
        // minDate: new Date().getTime(),
        formatter(type, value) {
          if (type === 'year') {
            return `${value}年`;
          } else if (type === 'month') {
            return `${value}月`;
          } else if (type === 'day') {
            return `${value}日`;
          }
          return value;
        },
        referList:[
            // {
            //     img: '/images/herder.png',
            //     name: '吴都峰',
            //     time: '10-01 14:20',
            //     address: '山东 济南—陕西 咸阳'
            // },
        ],// 推荐货主
        page: 1, // 推荐货主页数
        cargoId: '', // 货物id
        goods: [] ,// 获取 货物分类
    },
    onLoad: function (options) {
        this.getPlace();
        this.getType();// 筛选货物分类
        tab.tabbar("tabBar", 0, this)//0表示第一个tabbar
        this.initData(); // 装货地省市区 
        this.initDatas(); // 卸货地省市区
    },
    // 加载更多
    onReachBottom: function() {
        this.getReferList(this.data.page)
    },
    onShow: function () {
        this.getReferList();// 推荐货主
    },
    // 下拉刷新
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading(); 
        this.setData({
            // 把所选内容清空/重新赋值
            page: 1,
            province_zidz: '', // 装货省(调接口传值)
            city_zidz: '', // 装货市(调接口传值)
            area_zidz: '', // 装货区(调接口传值)
            region: '请选择装货地',
            installColor: '#999',
            installBold: '400',
            province_xidx: '', // 卸货省(调接口传值)
            city_xidx: '', // 卸货市(调接口传值)
            area_xidx: '', // 卸货区(调接口传值)
            regionTwo: "请选择卸货地",
            removeColor: '#999',
            removeBold: '400', 
            type: '', // 货物分类
            cargoId:'', // 货物id
            regionThree: ['必填，请输入货物分类'],
            mustColor: '#999', 
            time: '',  // 时间筛选
            regionFour: ['必填，请输入送货时间'],
            timeColor: '#999', 
            regionFours:'', // 时间显示
            showView: true,
            provinces_z: [],
            provinces_x: [],
        })
        this.getReferList(); // 货主列表
        this.getPlace(); // 获取地区
        this.initData(); // 装货地省市区 
        this.initDatas(); //卸货地省市区
    },
    // 装货地
    initData: function(){
        var provinces_z = [];
        var citys_z = [];
        var areas_z = [];
        this.data.citysData.forEach(function(province,i){
            provinces_z.push(province.name);
            if(i===0){
                citys_z.push(province.citys[i].name);
                citys_z.push(province.citys[1].name);
                areas_z = province.citys[i].areas;
            }
        });
        this.setData({
            provinces_z: provinces_z,
            citys_z: citys_z,
            areas_z: areas_z
        });
    },
    // 装货地 滑动
    bindChange: function(e){
        var citysData = this.data.citysData;
        var value = this.data.value_z;
        var current_value = e.detail.value;
        var citys = [];

        var provinceObj = {};
        var cityObj = {};

        provinceObj = citysData[current_value[0]];

        if (value[0] !== current_value[0]) {
            // 滑动省份
            provinceObj.citys.forEach(function(v){
                citys.push(v.name);
            });
            this.setData({
                citys_z: citys
            });

            cityObj = provinceObj.citys[0];
            this.setData({
                areas_z: cityObj.areas,
                value_z: [current_value[0],0,0]
            });

        }else if(value[0] === current_value[0] && value[1] !== current_value[1]){
            // 滑动城市
            if(current_value[1]>=provinceObj.citys.length){
                // 数据不存在 跳过
                return;
            }
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                areas_z: cityObj.areas,
                value_z: [current_value[0],current_value[1],0]
            });
        }else{
            // 滑动区县
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                value_z: current_value
            });
        }
        // console.log(this.data.value_z,'aaa')
        // console.log(cityObj.areas[this.data.value_z[2]],111)
        this.setData({
            province_zid: provinceObj.name, // 卸货省
            city_zid: cityObj.name, // 卸货市
            area_zid: cityObj.areas[this.data.value_z[2]], // 卸货区
            type_zid: 1
        });
    },
    //显示装卸货地
    showLoad(e) {
        // console.log(e)
        this.setData({
            type: e.currentTarget.dataset.type,
            showLoad: true
        })
    },
    // 关闭装卸货地
    onCloses(){
        this.setData({
            showLoad: false
        })
    },
    //取消装卸货地
    loadCancel() {
        this.setData({
            showLoad: false
        })
    },
    //装卸货地确定按钮
    loadConfirm(e) {
        if(this.data.type_zid == ''){
            this.setData({
                province_zid: '北京市',
                province_zidz: '北京市',
                city_zid: '',
            })
            this.setData({
                region: this.data.province_zid
            })
        }else{
            if(this.data.city_zid == '全部'){
                this.setData({
                    city_zid: '',
                    area_zid: ''
                })
            }
            if(this.data.area_zid == '全部'){
                this.setData({
                    area_zid: '',
                })
            }
            this.setData({
                region: this.data.province_zid+ ' '+this.data.city_zid+' '+this.data.area_zid,
                province_zidz:this.data.province_zid,
                city_zidz:this.data.city_zid,
                area_zidz:this.data.area_zid,
            })
        }
        this.setData({
            showLoad: false,
            page: 1,
            installColor: "#333",
            installBold: '700'
        })
        this.getReferList() 
        // console.log(this.data.province_zid,this.data.city_zid,this.data.area_zid)    
    },
    // 卸货地
    initDatas: function(){
        var provinces_x = [];
        var citys_x = [];
        var areas_x = [];
        this.data.citysData.forEach(function(province,i){
            
            provinces_x.push(province.name);
            if(i===0){
                citys_x.push(province.citys[i].name);
                citys_x.push(province.citys[1].name);
                areas_x = province.citys[i].areas;
            }
        });
        this.setData({
            provinces_x: provinces_x,
            citys_x: citys_x,
            areas_x: areas_x
        });
    },
    // 卸货地 滑动
    bindChanges: function(e){
        var citysData = this.data.citysData;
        var value = this.data.value_x;
        var current_value = e.detail.value;
        var citys = [];

        var provinceObj = {};
        var cityObj = {};

        provinceObj = citysData[current_value[0]];

        if (value[0] !== current_value[0]) {
            // 滑动省份
            provinceObj.citys.forEach(function(v){
                citys.push(v.name);
            });
            this.setData({
                citys_x: citys
            });

            cityObj = provinceObj.citys[0];
            this.setData({
                areas_x: cityObj.areas,
                value_x: [current_value[0],0,0]
            });

        }else if(value[0] === current_value[0] && value[1] !== current_value[1]){
            // 滑动城市
            if(current_value[1]>=provinceObj.citys.length){
                // 数据不存在 跳过
                return;
            }
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                areas_x: cityObj.areas,
                value_x: [current_value[0],current_value[1],0]
            });
        }else{
            // 滑动区县
            cityObj = provinceObj.citys[current_value[1]];
            this.setData({
                value_x: current_value
            });
        }
        this.setData({
            province_xid: provinceObj.name, // 卸货省
            city_xid: cityObj.name, // 卸货市
            area_xid: cityObj.areas[this.data.value_x[2]], // 卸货区
            type_xid: 1
        });
        // console.log(this.data.province_xid,this.data.city_xid,this.data.area_xid,1)
    },
     //显示卸货地
     showLoads(e) {
        this.setData({
            type: e.currentTarget.dataset.type,
            showLoads: true,
        })
    },
    // 关闭卸货地
    onClosesTwo(){
        this.setData({
            showLoads: false,
        })
    },
    //取消卸货地
    loadCancels() {
        this.setData({
            showLoads: false,
        })
    },
    //卸货地确定按钮
    loadConfirms(e) {
        if(this.data.type_xid == ''){
            this.setData({
                province_xid: '北京市',
                province_xidx: '北京市',
                city_xid: ''
            })
            this.setData({
                regionTwo: this.data.province_xid
            })
        } else {
            if(this.data.city_xid == '全部'){
                this.setData({
                    city_xid: '',
                    area_xid: ''
                })
            }
            if(this.data.area_xid == '全部'){
                this.setData({
                    area_xid: '',
                })
            }
            this.setData({
                regionTwo: this.data.province_xid+ ' '+this.data.city_xid+' '+this.data.area_xid,
                province_xidx:this.data.province_xid,
                city_xidx:this.data.city_xid,
                area_xidx:this.data.area_xidx,
            })
        }
        this.setData({
            showLoads: false,
            removeColor: '#333',
            removeBold: 700,
            page:1
        })
        // console.log(this.data.province_xidx)
        this.getReferList()      
    },
    // 货物分类 显示
    showPopupThree(){
        this.setData({ 
            showThree: true
        });
    },
    // 关闭
    onCloseThree(){
        this.setData({ 
            showThree: false
        });
    },
    // 改变
    onChangeThree(event) {
        const { picker, value, index } = event.detail;
        console.log(`当前值：${value}, 当前索引：${index}`);
    },
    // 确认
    onConfirmThree(event) {
        const { picker, value, index } = event.detail;
        this.setData({
            showThree: false,
            regionThree: event.detail.value,
            mustColor: '#333',
            cargoId : this.data.goods[event.detail.index].id,
            page: 1, 
        });
        this.getReferList()
    },
    // 取消
    onCancelThree() {
        console.log('取消');
        this.setData({ showThree: false });
    },
    // 时间筛选
    onInput(event) {
        this.setData({
          currentDate: event.detail,
        });
    },
    // 显示
    showPopupFour(){
        this.setData({ 
            showFour: true
        });
    },
     // 关闭
    onCloseFour() {
        this.setData({ 
            showFour: false
        });
    },
     // 确认
    onConfirmFour(event) {
        if(event.detail == ""){
            return ;
        }
        console.log(event)
        var date = this.getDate(event.detail);
        var arr = date.split(" ");
        var time = arr[0].split("-")
        const { picker, value, index } = event.detail;
        this.setData({ 
            showFour: false,
            regionFour: event.detail,
            timeColor: '#333',
            page: 1,
        });
        let year = time[0]; 
        var month = time[1];
        var day = time[2];
        if(month<10){ 
            month = '0'+month 
        }
        if( parseInt(day)<10){
            day = '0'+day  
        }
        this.setData({
            regionFours:  year + '-' + month + '-' +  day,
            regionFour:  year + '-' + month + '-' +  day
        })
        this.getReferList()
    },
    // 取消
    onCancelFour(){
        // console.log('取消1');
        this.setData({ 
            showFour: false
        });
    },
    // 改变
    onChangeFour(event) {
        const { picker, value, index } = event.detail;
        console.log(`当前值：${value}, 当前索引：${index}`);
    },
    // 推荐货主
    getReferList(){
        // console.log(this.data.page)
        var page = this.data.page
        wx.showLoading({
          title: '加载中···',
        })
        wx.request({
            url: app.globalData.url + 'api/v1/owner/owner/recommend',
            method: 'GET',
            data:{
                open_id: wx.getStorageSync('openid'),
                province_zid : this.data.province_zidz,
                city_zid: this.data .city_zidz,
                area_zid:this.data.area_zidz,
                province_xid : this.data.province_xidx,
                city_xid: this.data .city_xidx,
                area_xid: this.data.area_xidx,
                type: this.data.cargoId, 
                time: this.data.regionFours,
                page: page,
                limit: 10,
            },
            success: res => {
                if( res.data.code == 200 ){
                    wx.setStorageSync('id', res.data.data.data.id)
                    if ( page >1) {
                        if( res.data.data.data.info!= '' ){
                            this.setData({
                                referList: this.data.referList.concat(res.data.data.data.info),
                                page: page + 1
                            })
                        }
                    } else {
                        this.setData({
                             referList: res.data.data.data.info,
                             page: page + 1
                        })
                    }
                } else {
                    setTimeout(() => {
                        wx.showToast({
                            title: '没有更多数据',
                            icon: 'none',
                            mask: true
                        })
                    },500)
                }
            },
            fail: err => {
                console.log(err)
            },
            complete: () => {
                wx.hideLoading();
                wx.stopPullDownRefresh();
                wx.hideNavigationBarLoading();
            }
        })   
    },
     // 推荐货主详情
    goDetail(event){
        var id = event.currentTarget.dataset.id;
        var goodserId = event.currentTarget.dataset.goodser_id;
        wx.navigateTo({
          url: '/pages/car/index/idxDetail/idxDetail?id='+id+'&goodser_id='+goodserId,
        })
    },
    // 货物分类
    getType(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/gettype',
            method: 'GET',
            data:{
            },
            success: res => {
                var columns = []
                for(var i = 0 ; i < res.data.data.length ; i++ ){
                    columns = columns.concat(res.data.data[i].name)
                }
                this.setData({
                    columns: columns, //name
                    goods: res.data.data  //id
                })
            },
            fail: err => {
              console.log(err)
            },
        })
    },
    // 时间戳
    getDate(unixtime) {
        var dateTime = new Date(parseInt(unixtime))
        var year = dateTime.getFullYear();
        var month = dateTime.getMonth() + 1;
        var day = dateTime.getDate();
        var now = new Date();
        var now_new = Date.parse(now.toDateString()); 
        var milliseconds = now_new - dateTime;
        var timeSpanStr = year + '-' + month + '-' + day 
        return timeSpanStr;
    },
    // 地区
    getPlace(){
        wx.request({
            url: app.globalData.url + 'api/v1/news/regions',
            method: 'get',
            data:{},
            success: res => {
                console.log(res,8889)
                this.setData({
                    citysData: res.data.data
                })
                this.initData(); // 装货地省市区 
                this.initDatas(); // 卸货地省市区
            },
            fail: err => {
              console.log(err)
            },
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },


    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    } 
})